const db = require('./db')
const R = require('ramda')
const Node = require('./Node')

const me = {
  get_with_default: nodeId => {
    return new Promise((resolve, reject) => {
      me.get_by_node_id(nodeId).then(articles => {
        if (R.isEmpty(articles)) {
          me.add_new(nodeId).then(res => {
            me.get_by_node_id(nodeId).then(articles => {
              resolve(articles[0])
            })
          })
        } else {
          resolve(articles[0])
        }
      })
    })
  },
  get_by_node_id: nodeId => {
    return new Promise((resolve, reject) => {
      db.query('select * from article where node_id=? limit 1', [nodeId]).then(resolve)
    })
  },
  add: (nodeId, title, content) => {
    console.log('add: nodeId:' + nodeId + ' title:' + title + ' content:' + content)
    return new Promise((resolve, reject) => {
      db.query('insert into article(node_id,title,content,update_time) values(?,?,?,NOW())', [nodeId, title, content]).then(res => {
        console.log('Add article: ')
        console.log(res)
        resolve(true)
      })
    })
  },
  add_new: nodeId => {
    return new Promise((resolve, reject) => {
      //TODO: 插入一个新的文章节点
      Node.get(nodeId).then(node => {
        console.log('add new: nodeId:' + nodeId + ' node:' + JSON.stringify(node))
        me.add(node.id, node.title, "还没有内容").then(result => {
          resolve(result)
        })
      })
    })
  },
  update_by_node:  (nodeId,title,content) => {
    return new Promise((resolve,reject) => {
      db.query('update article set title=?,content=?,update_time=NOW() where node_id=?',[title,content,nodeId]).then(res => {
        db.query('update node set title=? where id=?',[title,nodeId]).then(res => {
          resolve(true)
        })
      })
    })
  },
  del: id => {
    return new Promise((resolve,reject) => {
      db.query('delete from article where id=?',[id]).then(resolve)
    })
  }
}

module.exports = me